package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAgentDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosOrderDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.SpringUtil;

@Service
public class KitePosAgentHandler extends KitePosSceneHandler {

	@Override
	public void handle(KitePosHandlerContext context) {
		IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
		KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
		String serviceOfferId = (String) Optional
                .ofNullable(querySceneInstService.getSceneInst(context.getSceneInstId()))
                .map(KiteSceneInst::getServiceOfferId).orElse("");
		if (StringUtils.equalsAny(kiteSceneInst.getOperType(), LocalKeyConsts.SCENE_OPER_TYPE_ORDER_SIGN, LocalKeyConsts.SCENE_OPER_TYPE_TRANSFER_PLAN_MODIFY)) {
			return;
		}
        String cateId = CuccPosServiceUtils.getCateId(context.getSceneInstId(), context.getCustId());
		List<KiteAttr> publicAttrs = querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.MODULE_ID_PUBLIC);
        KiteAttr agentAttrObj = publicAttrs.stream().filter(attr -> KiteStringUtils.equals(attr.getFieldName(), "AgentInfo")).findFirst().orElse(null);
        if(Objects.nonNull(agentAttrObj)) {
            List<KiteAttr> agentAttrs = querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.MODULE_ID_AGENT);
            if (KiteListUtils.isEmpty(agentAttrs)) {
                if (LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW.equals(serviceOfferId)) {
                    return;
                }
                else {
                    ErrorConsts.BUSI_COMMON_ERROR.throwOut("未配置【代理人】属性");
                }
            }
            KitePosAgentDTO agent = new KitePosAgentDTO();
            agent.setAgentChannelId(this.getAttrValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CHANNELID, "未配置【代理商渠道ID】属性"));
            agent.setAgentChannelName(this.getAttrValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CHANNELNAME, "未配置【代理商渠道名称】属性"));
            agent.setAgentIdType(this.getAttrValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CARDTYPE, "未配置【代理商证件类型】属性"));
            agent.setAgentIdNo(this.getAttrValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CARDNUM, "未配置【代理商证件号码】属性"));
            agent.setAgentAddress(this.getAttrValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CARDADDRESS, "未配置【代理商证件地址】属性"));
            agent.setAgentId(this.getAttrValue(agentAttrs, LocalKeyConsts.AGENT_INFO_ID, "未配置【代理商ID】属性"));
            agent.setAgentName(this.getAttrValue(agentAttrs, LocalKeyConsts.AGENT_INFO_NAME, "未配置【代理商名称】属性"));
            agent.setAgentPhone(this.getAttrValue(agentAttrs, LocalKeyConsts.AGENT_INFO_TEL, "未配置【代理商联系方式】属性"));
            /*
             * 对接用户中心改造：需要新增changeType、startDate、endDate字段
             */
            if (CuccPosServiceUtils.isRouteUser(context.getSceneInstId(),context.getCustId())) {
                KitePosAgentDTO oldAgent = querySceneInstService
                        .getExtParameterValue(context.getSceneInstId(), "agent");
                if(!KiteStringUtils.equals(agentAttrObj.getValue(), "T")) {
                    // 未选中的情况下，判断是否存在旧值，存在则说明此次操作非订购需删除，不存在则说明此次不调整代理商。
                    if(KiteStringUtils.isEmpty(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CHANNELID, ""))) {
                        return ;
                    }
                    agent.setAgentChannelId(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CHANNELID, "未配置【代理商渠道ID】属性"));
                    agent.setAgentChannelName(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CHANNELNAME, "未配置【代理商渠道名称】属性"));
                    agent.setAgentIdType(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CARDTYPE, "未配置【代理商证件类型】属性"));
                    agent.setAgentIdNo(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CARDNUM, "未配置【代理商证件号码】属性"));
                    agent.setAgentAddress(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CARDADDRESS, "未配置【代理商证件地址】属性"));
                    agent.setAgentId(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_ID, "未配置【代理商ID】属性"));
                    agent.setAgentName(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_NAME, "未配置【代理商名称】属性"));
                    agent.setAgentPhone(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_TEL, "未配置【代理商联系方式】属性"));
                    agent.setChangeType(ChangeTypeUtils.CHANGE_TYPE_D);
                    if(Objects.nonNull(oldAgent)) {
                        agent.setStartDate(oldAgent.getStartDate());
                        // 删除的结束时间为当前时间或不传
                        //agent.setEndDate(oldAgent.getEndDate());
                    }
                }else {
                    // 非订购的情况下，需要传changeType、startDate、endDate字段
                    if (CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                        if(KiteStringUtils.isEmpty(this.getAttrOriginValueValue(agentAttrs, LocalKeyConsts.AGENT_INFO_CHANNELID, ""))) {
                            agent.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
                        }else {
                            if(Objects.nonNull(oldAgent)) {
                                agent.setStartDate(oldAgent.getStartDate());
                                agent.setEndDate(oldAgent.getEndDate());
                            }
                            List<KiteAttr> changeKiteAttr = agentAttrs.stream().filter(attr -> !KiteStringUtils.equals(attr.getOriginValue(), attr.getValue())).collect(Collectors.toList());
                            if(KiteListUtils.isEmpty(changeKiteAttr)) {
                                agent.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);

                                if(Objects.nonNull(oldAgent) && KiteStringUtils.equals(ChangeTypeUtils.CHANGE_TYPE_M, oldAgent.getChangeType())) {
                                    if(KiteStringUtils.equals(serviceOfferId, "2826")) {
                                        String nodeCode = querySceneInstService.getExtParameterValue(context.getSceneInstId(), "nodeCode");
                                        if(KiteStringUtils.equals(nodeCode, "OrderSigned")) {
                                            // 产品变更-签订，获取第一次提交时的changeType
                                            agent.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                                        }
                                    }
                                }
                            }else {
                                agent.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                            }
                        }
                    } else {
                        // 订购，资源核查等情况
                        if (KiteStringUtils.isEmpty(agent.getChangeType())) {
                            agent.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
                        }
                    }
                }
            }
            dealAgent(context,kiteSceneInst,agent) ;
        }
	}

	private void dealAgent(KitePosHandlerContext context,KiteSceneInst kiteSceneInst,KitePosAgentDTO agent) {
	    // 渠道ID，为空，则不传
	    if (KiteStringUtils.isEmpty(agent.getAgentChannelId())) {
	        return ;
	    }
		Date createDate = kiteSceneInst.getCreateDate();
		String createDateStr = KiteDateUtils.formatDate(createDate, KiteDateUtils.DATE_TIME_FORMAT_14);
		KitePosOrderDTO order = context.getPosDto().getOrder();
		if (Objects.isNull(order)) {
			order = new KitePosOrderDTO();
		}
		List<KitePosAttrDTO> attrs = order.getAttrs();
		if (KiteListUtils.isEmpty(attrs)) {
			attrs = new ArrayList<>();
		}

        KitePosAttrDTO agentAttr = attrs.stream().filter(attr -> KiteStringUtils.equals("agent", attr.getCode())).findFirst().orElse(null);
		if(Objects.isNull(agentAttr)){
            agentAttr = new KitePosAttrDTO();
            agentAttr.setCode("agent");
            agentAttr.setType("OBJECT");
            agentAttr.setValue(JSONObject.toJSONString(agent));
            agentAttr.setStartDate(createDateStr);
            agentAttr.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
            attrs.add(agentAttr);
        }
        else{
            agentAttr.setType("OBJECT");
            agentAttr.setValue(JSONObject.toJSONString(agent));
            agentAttr.setStartDate(createDateStr);
            agentAttr.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
        }
		order.setAttrs(attrs);
		context.getPosDto().setOrder(order);
	}

}
